#include "addcategory.h"
#include "ui_addcategory.h"

AddCategory::AddCategory(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddCategory)
{
    ui->setupUi(this);

    editFlag=false;
    model=new QStandardItemModel(this);
    model->setHorizontalHeaderLabels(QStringList() << "属性名" << "显示名");
    ui->tableView->setModel(model);
}

AddCategory::~AddCategory()
{
    delete ui;
}

void AddCategory::setItem(const QString &category,
                          const QStringList &properties,
                          const QStringList &columns)
{
    if(category.isEmpty())
        return;

    editFlag=true;
    ui->category->setText(category);
    ui->category->setEnabled(false);
    ui->btn_submit->setText("保存");

    _properties=properties;
    _columns=columns;

    for (int i = 0; i < properties.size(); ++i) {
        QList<QStandardItem *> row={
            new QStandardItem(properties.at(i)),
            new QStandardItem(columns.value(i))
        };
        model->appendRow(row);
    }
}

void AddCategory::on_btn_submit_clicked()
{
    QString category=ui->category->text().trimmed();
    if(category.isEmpty())
        return;

    if(model->rowCount() < 1)
        return;

    QJsonObject obj;
    obj.insert("category",category);

    QStringList properties;
    QStringList columns;

    for (int i = 0; i < model->rowCount(); ++i) {
        properties.append(model->item(i,0)->text());
        columns.append(model->item(i,1)->text());
    }

    if(properties.isEmpty())
        return;

    if(!editFlag)
    {
        obj.insert("properties",QJsonArray::fromStringList(properties));
        if(!columns.first().isEmpty())
            obj.insert("columns",QJsonArray::fromStringList(columns));

        emit addItem(obj);
    }
    else {
        QJsonObject updater;
        if(_properties != properties)
            updater.insert("properties",QJsonArray::fromStringList(properties));

        if(_columns != columns)
            updater.insert("columns",QJsonArray::fromStringList(columns));

        if(updater.isEmpty())
            return;

        QJsonArray array;
        array.append(obj);
        array.append(updater);

        emit updateItem(array);
    }
    accept();
}

void AddCategory::on_btn_add_clicked()
{
    QString property=ui->property->text().trimmed();
    if(property.isEmpty())
        return;

    QString column=ui->column->text().trimmed();
    QList<QStandardItem *> row={
        new QStandardItem(property),
        new QStandardItem(column)
    };

    model->appendRow(row);
    ui->property->clear();
    ui->column->clear();
}

void AddCategory::on_btn_remove_clicked()
{
    QModelIndex index=ui->tableView->currentIndex();
    if(index.isValid())
        model->removeRow(index.row());
}
